<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getBorrowList, returnBook } from '@/api/borrow'
import type { Borrow, BorrowQueryParams } from '@/types/borrow'
import { ElMessage, ElMessageBox } from 'element-plus'
import { usePagination } from '@/composables/usePagination'

// 查询参数
const queryParams = ref<BorrowQueryParams>({
  pageNum: 1,
  pageSize: 10,
  status: undefined
})

// 借阅记录列表
const borrowList = ref<Borrow[]>([])
const total = ref(0)

// 分页
const { pageNum, pageSize, onSizeChange, onCurrentChange } = usePagination(() => fetchBorrows())

// 获取借阅记录
const fetchBorrows = async () => {
  try {
    const params = {
      ...queryParams.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    const response = await getBorrowList(params)
    if (!response?.data) {
      throw new Error('无效的API响应: 缺少data字段')
    }
    borrowList.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('获取借阅记录失败:', error)
    ElMessage.error('获取借阅记录失败')
    borrowList.value = []
    total.value = 0
  }
}

// 归还图书
const handleReturn = async (borrowId: number) => {
  try {
    await ElMessageBox.confirm('确认归还图书吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await returnBook(borrowId)
    ElMessage.success('归还成功')
    fetchBorrows() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('归还失败:', error)
      ElMessage.error('归还失败')
    }
  }
}

// 初始化加载数据
onMounted(() => {
  fetchBorrows()
})
</script>

<template>
  <div class="borrow-list-container">
    <el-card>
      <template #header>
        <div class="header">
          <span>借阅记录</span>
          <el-button type="primary" @click="fetchBorrows">刷新</el-button>
        </div>
      </template>

      <div class="filter">
        <el-radio-group v-model="queryParams.status" @change="fetchBorrows">
          <el-radio-button :label="undefined">全部</el-radio-button>
          <el-radio-button :label="0">借阅中</el-radio-button>
          <el-radio-button :label="1">已归还</el-radio-button>
        </el-radio-group>
      </div>

      <el-table :data="borrowList" border style="width: 100%">
        <el-table-column prop="bookTitle" label="书名" width="180" />
        <el-table-column prop="borrowDate" label="借阅日期" width="180">
          <template #default="{ row }">
            {{ new Date(row.borrowDate).toLocaleDateString() }}
          </template>
        </el-table-column>
        <el-table-column prop="expectedReturnDate" label="预计归还日期" width="180">
          <template #default="{ row }">
            {{ new Date(row.expectedReturnDate).toLocaleDateString() }}
          </template>
        </el-table-column>
        <el-table-column prop="returnDate" label="实际归还日期" width="180">
          <template #default="{ row }">
            {{ row.returnDate ? new Date(row.returnDate).toLocaleDateString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="warning">借阅中</el-tag>
            <el-tag v-else type="success">已归还</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 0"
              type="primary"
              size="small"
              @click="handleReturn(row.borrowId)"
            >
              归还
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.borrow-list-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
